<template>
	<view>
		<ScrollPage :keyboardChange="keyboardChange"  @scrolltolower="nextPage">
			<template #content>
				<view>
					<!-- 搜索 -->
					<view class="w100" style="padding: 10px 15px 25px 15px">
						<up-form labelPosition="left" labelWidth="90" labelAlign="right">
							<up-form-item label="昵称：">
								<up-input border="surround" v-model="query.nickname" clearable></up-input>
							</up-form-item>
							<up-form-item label="用户ID：">
								<up-input border="surround"  placeholder="支持模糊查询" v-model="query.userId" clearable></up-input>
							</up-form-item>
							<up-form-item label="手机号：">
								<up-input border="surround" v-model="query.phone" clearable></up-input>
							</up-form-item>
							<up-form-item label="国籍：">
								<view class="w100 relative">
									<up-input border="surround" v-model="query.countryNameCn"></up-input>
									<view class="hw100  bg-transparency absolute" style="height: 40px; left:0; top:0;" @click="showNationality"></view>
								</view>
							</up-form-item>
							<up-form-item label="代理商ID：">
								<up-input border="surround"  placeholder="支持模糊查询" v-model="query.masterId" clearable></up-input>
							</up-form-item>
							<up-form-item label="创建时间：">
								<view class="w100 relative">
									<up-input border="surround"  v-model="query.date"></up-input>
									<view class="hw100  bg-transparency absolute" style="height: 40px; left:0; top:0;" @click="showPicker"></view>
								</view>
							</up-form-item>
						</up-form>
						<view class="w100 text-center">
							<button class="cu-btn line-gray" @click="searchClean">
								<text class="iconfont icon-delete margin-right-10"></text> 
								<text>重<text class="padding-lr-20"></text>置</text>
							</button>
							<text class="padding-lr-20"></text>
							<button class="cu-btn line-keyblue " @click="confirmSearch">
								<text class="iconfont icon-sousuo margin-right-10"></text> 
								<text>搜<text class="padding-lr-20"></text>索</text>
							</button>
						</view>
					</view>
                    <!-- 内容区 -->
					<view>
						<template v-if="dataList.length > 0">
							<view class="outline lightBlue ">
								<template v-for="(item,index) in dataList" :key="item.userId">
									<view class="flex-row row " style="padding: 15px 5px;">
										<!-- 左边 -->	
										<view class="flex-col">
											<MeImage @click="previewSingleImage(item.avatar)"   :src="item.avatar" width="48px" height="48px" radius="5" :lazy-load="true"></MeImage >
											<MeImage  :src="item.nationalFlagUrl" class="margin-tb-20" width="48px" height="48px"  mode="aspectFit" :lazy-load="true"></MeImage >
										</view>
										<!-- 右边 -->
										<view class="flex-col flex-sub relative" style="margin-left: 10px;">
											<view class="absolute padding-10 text-gray font-s15 " style="top: 5px;right: 5px;">
												<text>{{ index + 1 }}</text>
											</view>
											<view class="flex-row">
												<text class="text-bold">昵称:</text>
												<text v-if="item.nickname" class="margin-left-10  text-lightGreyblue text-bold">{{item.nickname}}</text>
												<text v-else class="margin-left-10  text-gray81">未知状态</text>
											</view>
											<view class="margin-tb-5" >
												<text class="text-bold">是否在线:</text>
												<text v-if="item.onlineStatus === 0" class="text-gray81 margin-left-10">离线</text>
												<text v-else class="text-green margin-left-10">在线</text>
											</view>
											<view class="margin-tb-5" >
												<text class="text-bold">状态:</text>
												<text v-if="item.status === 0" class="text-gray51 margin-left-10">新用户(未提交主播资质申请)</text>
												<text v-else-if="item.status === 1" class="text-green margin-left-10">正常(主播资质审核通过)</text>
												<text v-else-if="item.status === 2" class="text-red margin-left-10">下架</text>
												<text v-else-if="item.status === 3" class="text-red margin-left-10">冻结</text>
												<text v-else-if="item.status === 4" class="text-red margin-left-10">已删除</text>
												<text v-else-if="item.status === 5" class="text-orange margin-left-10">主播资质审核中</text>
												<text v-else-if="item.status === 6" class="text-orange margin-left-10">主播资质审核未通过</text>
												<text v-else class="text-gray81 margin-left-10">未知状态</text>
											</view>
											<view v-if="item.nationality" class="margin-tb-5" >
												<text class="text-bold">国籍:</text>
												<text class="margin-left-10 ">{{item.nationality}}</text>
												<text class="margin-left-10 text-gray font-s22">({{item.countryCode}})</text>
											</view>
											<view class="margin-tb-5" >
												<text class="text-bold">是否隐藏:</text>
												<text v-if="item.isHide === False" class="text-green margin-left-10">否</text>
												<text v-else-if="item.isHide === True" class="text-orange margin-left-10">是</text>
											</view>
											<view class="margin-tb-5" >
												<text class="text-bold">用户ID:</text>
												<text class="margin-left-10">{{item.userId}}</text>
											</view>
											<view class="margin-tb-5" >
												<text class="text-bold">手机号:</text>
												<text class="margin-left-10">{{item.phone}}</text>
											</view>
											<view class="margin-tb-5" >
												<text class="text-bold">APP ID:</text>
												<text class="margin-left-10">{{item.appId}}</text>
											</view>
											<view class="margin-tb-5" >
												<text class="text-bold">生日:</text>
												<text v-if="item.birthday" class="margin-left-10">{{item.birthday}}</text>
												<text v-else class="margin-left-10  text-gray81">未知状态</text>
											</view>
											<!-- <up-line margin="5px 0" :dashed="true"></up-line> -->
											<view class=" margin-tb-5" >
												<text class="text-bold">视频通话价格:</text>
												<text v-if="item.chatPrice" class="margin-left-10">{{item.chatPrice}} 金币/分钟</text>
												<text v-else class="margin-left-10  text-gray81">未知状态</text>
											</view>
											<view class="margin-tb-5" >
												<text class="text-bold">好友数:</text>
												<text  class="margin-left-10">{{item.friends}} 位</text>
											</view>
											<view class="margin-tb-5" >
												<text class="text-bold">视频通话数:</text>
												<text  class="margin-left-10">{{ Math.round(item.callVolume / 60)}} 分钟</text>
											</view>
											<view class="margin-tb-5" >
												<text class="text-bold">收到礼物数:</text>
												<text  class="margin-left-10">{{item.gifts}} 个</text>
											</view>
											<template v-if="item.masterId">
												<view class="margin-tb-5" >
													<text class="text-bold">归属代理ID:</text>
													<text  class="margin-left-10">{{item.masterId}}</text>
												</view>
												<view class="margin-tb-5" >
													<text class="text-bold">归属代理名称:</text>
													<text  class="margin-left-10">{{item.orgName}}</text>
												</view>
											</template>
											<!-- <up-line margin="5px 0" :dashed="true"></up-line> -->
											<view class="flex-col  margin-tb-5 w100" >
												<text class="text-bold font-s32">简介</text>
												<view v-if="item.signature" class=" text-indent text-justify lh-105  margin-tb-10 padding-10 radius-10">
													<text  class="text-gray51">{{item.signature}}</text>
												</view>
												<view v-else class=" text-indent text-justify lh-105 text-gray81">
													 <text>暂无信息</text>
												</view>
											</view>
											<view class="flex-col  margin-tb-5 w100" >
												<text class="text-bold font-s32">视频</text>
												<view v-if="item.videoUrl" class="flex-col margin-tb-10" style="width: 148px; height: 148px" @click="toPlay(item.videoUrl, item.videoPosterUrl)">
													<template v-if="item.videoPosterUrl" >
														<view style="width: 148px; height: 148px;" >
															<MeImage   :src="item.videoPosterUrl" width="148px" height="148px" radius="5" :lazy-load="true"></MeImage >
														</view>
													</template>
													<template v-else>
														<view class="relative solid-border-gray91 radius-10" style="width: 148px; height: 148px">
															<text class="iconfont icon-zanwutupian absolute" style="color: #E8E8E8; font-size: 58px; top: 39px; left: 49px"></text> 
														</view>
													</template>
												</view>
												<view v-else class=" text-indent text-justify lh-105 text-gray81">
													<text>暂无视频</text>
												</view>
											</view>
											<view class=" margin-tb-5" >
												<text class="text-bold">创建时间:</text>
												<text class="margin-left-10">{{ item.createTime }}</text>
											</view>
											<template v-if="item.updateTime">
												<view class=" margin-tb-5" >
													<text class="text-bold">更新时间:</text>
													<text class="margin-left-10">{{ item.updateTime }}</text>
												</view>
											</template>
											<!-- <up-line margin="5px 0" :dashed="true"></up-line> -->
											<!-- 操作 -->
											<view class="flex-row flex-wrap">
												<button class="cu-btn line-blue sm margin-10" @click="viewAlbum(item.userId)">查看专辑</button>
												<button v-if="item.status == Normal || item.status == Hide" @click="switchStatus(item.userId, SoldOut)" class="cu-btn line-red sm margin-10">主播下架</button>
												<button v-else-if="item.status == SoldOut" @click="switchStatus(item.userId, Normal)" class="cu-btn line-green sm margin-10">主播上架</button>
												<button v-if="item.isHide == True" class="cu-btn line-darkCyan sm margin-10" @click="switchHide(item.userId, False)">显示</button>
                                                <button v-else class="cu-btn line-yellow sm margin-10" @click="switchHide(item.userId, True)">隐藏</button>   
												<button @click="showMaster(item.userId)" class="cu-btn line-purple sm margin-10">归属代理商</button>
												<button class="cu-btn line-green sm margin-10" @click="changeAvatar(item.userId)">更换头像</button>   
												<button class="cu-btn line-black sm margin-10" @click="synToYunXin(item.userId)">同步IM</button>   
												<button class="cu-btn line-gray sm margin-10" @click="flush(item.userId)">刷新</button>   
											</view> 
										</view>
									</view>
								</template>
							</view>
							<view v-if="!loadding" class="h600 flex-col align-center">
								<view class="h64"></view>
								<button class="cu-btn line-blue" :disabled="dataList.length >= query.totalSize" @click="nextPage">加载更多数据</button>
							</view>
						</template>
						<!-- 暂无数据 -->
						<template v-else>
							<view v-if="!loadding" class="h300 w100 flex-col-center text-gray81">
								<text class="iconfont icon-zanwushuju2" style="font-size: 125px;"></text>
							</view>
						</template>
					</view> 
					<!-- 添加按钮，右下角 -->
					<view  style="position:fixed;right: 10px; top: 80%;">
						<view class="flex-col-center text-white bg-keyblue round-half" hover-class="selected bg-select" @click="toAddAnchor"> 
							<view class="hw96 flex-col-center" >
								<text class="cuIcon-add" style="font-size: 39px;"></text>
							</view>
						</view>
					</view>
				</view>
			</template>
		</ScrollPage>
		<up-datetime-picker ref="datePicker"  :formatter="formatter"    :show="showDatePicker"  @cancel="cancelPicker" v-model="dataPickerValue"  
	   					cancelColor="red" @confirm="confirmSelectDate" mode="date"></up-datetime-picker>
		<!-- 选择国籍 -->
		<up-popup :show="showNationalityPopup" mode="bottom" :minHeight="popupHeight + 'px' " :maxHeight="popupHeight + 'px' " @close="closeNationalityEvent" @open="openNationalityEvent">
			<view :style="{height: popupHeight + 'px' }">
				<view class="flex-row-center solid-bottom-yellow" :style="{height: 60 + 'px', padding: '0px 15px' }">
                   <up-search  :adjustPosition="false" placeholder="国家中文或英文名称" @change="searchNationaly" v-model="keyword"></up-search>
				</view>
				<view>
					<scroll-view scroll-y  :style="{height: popupHeight - 60 + 'px' }">
						<view class="outline padding-lr-30">
							<template v-for="item in nationalList" :key="item.id">
                                 <view class="flex-row  padding-tb-10 row" hover-class="bg-select" @click="selectNational(item.id)">
									<MeImage  fontSize="8px" :lazy-load="true"  :src="item.flagUrl" width="32px" height="32px"  mode="aspectFit"></MeImage >
                                    <view class="flex-col">
										 <view class="flex-row align-baseline">
											<text class="margin-left-15">{{item.countryNameCn}}</text>
											<text class="font-s21 text-gray">({{item.phoneCode}}.{{item.countryCode}})</text>
										 </view>
										 <text class="margin-lr-15 font-s21">{{item.countryNameEn}}</text>
									</view>
								 </view>
							</template>
						</view>
					</scroll-view>
				</view>
			</view>
		</up-popup>
		<!-- 归属代理商  -->
		<up-popup :show="showMasterPopup" mode="bottom" :minHeight="popupHeight + 'px' " :maxHeight="popupHeight + 'px' " @close="closeMaterEvent" @open="openMasterEvent">
			<view :style="{height: popupHeight + 'px' }">
				<view class="flex-row-center solid-bottom-yellow" :style="{height: 60 + 'px', padding: '0px 15px' }">
                   <up-search :adjustPosition="false"  placeholder="输入代理商名称或ID"  @change="searchMaster" v-model="masterQuery.keyword"></up-search>
				</view>
				<view>
					<scroll-view scroll-y  :style="{height: popupHeight - 60 + 'px' }">
						<view class="outline ">
							<template v-for="item in masterDataList" :key="item.id">
                                 <view class="flex-row justify-between  padding-30 row" hover-class="bg-select" @click="showEidtMasterModal(item.id)">
                                    <view class="flex-col">
										 <view class="flex-row align-baseline">
											<text class="margin-left-15">{{item.orgName}}</text>
											<text class="font-s21 text-gray">({{item.masterId}})</text>
										</view>
									</view>
									<view class="flex-row align-baseline">
											<text class="margin-left-15 font-s25">成员</text>
											<text class="font-s21 text-gray">({{item.memberCount}} 人)</text>
									</view>
								 </view>
							</template>
						</view>
					</scroll-view>
				</view>
			</view>
		</up-popup>
		<!-- 确定使用代理商 -->
		<view class="cu-modal" :class="isShowMasterModel ? 'show' : '' ">
			<view class="cu-dialog bg-white">
				<view class="padding-25 font-s38 text-orange">
					<text>修改提示</text>
				</view>
				<view class="padding-25 text-center">
					<view>确定使用代理商<text class="text-bold">{{editMasterForm.orgName}}?</text></view>
				</view>
				<view class="padding-25 flex-row justify-end w100">
					<button class="cu-btn line-grey margin-lr-10" @click="hideMasterModal">取消</button>
					<button class="cu-btn line-red margin-lr-10" @click="confirmEditMaster">确定</button>
				</view>
			</view>
		</view>
	</view>
</template>
<script setup lang="ts">
import { reactive, ref } from 'vue'
import { onLoad , onUnload  } from "@dcloudio/uni-app"
import { storeToRefs } from 'pinia'
import { showError, showToast } from '@/utils/msg-show'
import { previewSingleImage } from '@/utils/img'
import { navigate } from "@/security/router"
import { textToUrlCode } from "@/utils/strUtil"
import { urls } from "@/security/paths"
import { debounce } from "@/utils/util"
import { Normal, SoldOut, Hide, True, False } from '@/utils/keyWord'
import { formatter, convertDateFormat } from '@/utils/util'
import { switchStatusApi, switchHideApi, getOneApi } from '@/api/anchor/list'
import { synToYunXinApi } from '@/api/user/list'
import { editLaborUnionApi } from "@/api/sys/organization"
import { useAnchorListStore } from '@/store'
import { useNationalStore } from '@/store'

const anchorListStore = useAnchorListStore()
const nationalStore = useNationalStore()

const { query, dataList, masterDataList, masterQuery } = storeToRefs(anchorListStore)
const { nationalList, nationalListCopy } = storeToRefs(nationalStore)

const windowInfo = uni.getWindowInfo()
const screenHeight = windowInfo.screenHeight

const popupHeight = screenHeight - Math.floor(screenHeight / 4) 

const loadding = ref(false)
const keyboardChange = ref(false)
const keyword = ref()

const datePicker = ref()
const showDatePicker = ref(false)
const today = new Date()
const dataPickerValue = ref(today.getTime())

const showNationalityPopup = ref(false)
const showMasterPopup = ref(false)
const isShowMasterModel = ref(false)

const updateId = ref()

const editMasterForm = reactive<any>({
	memberId: "",
	masterId: '',
	orgName: ''
})

// 跳转到播放视频
function toPlay(videoUrl: string, posterUrl: string){
  navigate(`${urls.Play}?videoUrl=${textToUrlCode(videoUrl)}&posterUrl=${textToUrlCode(posterUrl)}`)
}

// 跳转到添加主播 AddAnchor
function toAddAnchor(){
	navigate(urls.AddAnchor)
}

// 显示国籍框
function showNationality(){
	uni.hideTabBar({
		animation:true,
		success: ()=>{
            showNationalityPopup.value = true
			keyboardChange.value = false
		}
	})
}

// 刷新用户信息
async function flush(userId: string){
	uni.showLoading({mask: true})
	await getOneApi({userId}).then((res:any) => {
		const index = dataList.value.findIndex(e=>e.userId == userId)
		if(index != -1){
			dataList.value[index] = res.data
		}
	}).catch((err: any) => {
		showError(err.msg || err.errMsg || err)
	}).finally(()=>{
		uni.hideLoading()
	})
}

// 用户信息同步云信平台
async function synToYunXin(userId: string){
	uni.showLoading({mask: true})
	await synToYunXinApi({userId}).then((res:any) => {
		showToast("同步成功", 500)
	}).catch((err: any) => {
		showError(err.msg || err.errMsg || err)
	}).finally(()=>{
		uni.hideLoading()
	})
}


// 显示搜索代理商
function showMaster(userId: string){
	uni.hideTabBar({
		animation:true,
		success: ()=>{
			// 对应需要修改的主播
			editMasterForm.memberId = userId

            showMasterPopup.value = true
			keyboardChange.value = false
		}
	})
}

// 显示修改代理商提示
function showEidtMasterModal(id: number){
	const target = masterDataList.value.find(e => e.id == id)
	if(target){
		editMasterForm.masterId = target.masterId
		editMasterForm.orgName = target.orgName
		closeMaterEvent()
		isShowMasterModel.value = true
	}
}

// 打开国籍模态框事件
function openNationalityEvent(){
	uni.hideTabBar({
		animation:true,
		success: ()=>{
            showNationalityPopup.value = true
			keyboardChange.value = false
		}
	})
}

// 打开代理商模态框事件
function openMasterEvent(){
	uni.hideTabBar({
		animation:true,
		success: ()=>{
            showMasterPopup.value = true
			keyboardChange.value = false
		}
	})
}

// 关闭国籍模态框事件
function closeNationalityEvent(){
	uni.showTabBar({
		animation:true,
		success: ()=>{
			showNationalityPopup.value = false
			keyboardChange.value = true
		}
	})
}

// 关闭代理商模态框事件
function closeMaterEvent(){
	uni.showTabBar({
		animation:true,
		success: ()=>{
			showMasterPopup.value = false
			keyboardChange.value = true
		}
	})
}

// 隐藏修改代理商提示框
function hideMasterModal(){
	isShowMasterModel.value = false
}

// 显示picker
function showPicker(){
    uni.hideTabBar({
		animation:true,
		success: ()=>{
            showDatePicker.value = true
		}
	})
}

// 取消picker窗口
function cancelPicker(){
  	uni.showTabBar({
		animation:true,
		success: ()=>{
			showDatePicker.value = false
		}
	})
}

// 确定修改代理
async function confirmEditMaster(){
	uni.showLoading({mask: true})
	await editLaborUnionApi(editMasterForm).then((res:any) => {
		const target = dataList.value.find(e=>e.userId == editMasterForm.memberId)
		if(target){
             target.masterId = editMasterForm.masterId
             target.orgName = editMasterForm.orgName
		}
	}).catch((err: any) => {
        showError(err.msg || err.errMsg || err)
    }).finally(()=>{
        uni.hideLoading()
		hideMasterModal()
    })
}

// 确定选择日期
function confirmSelectDate(val: any){
	const timestamp = val.value
    const date = new Date(timestamp)
    query.value.date = convertDateFormat(date)
	// animation	是否需要动画效果，仅小程序支持
	uni.showTabBar({
		animation:true,
		success: ()=>{
              showDatePicker.value = false
		}
	})
}

// 确定选择国籍
function selectNational(id: number){
	const target = nationalList.value.find((e) => e.id == id)
	if(target){
        query.value.countryNameCn = target.countryNameCn
        query.value.national = target.countryNameEn

		closeNationalityEvent()
	}
}

// 搜索国籍
const searchNationaly  = debounce(()=>{
   nationalList.value = nationalListCopy.value.filter( (obj: any) => obj.countryNameCn.includes(keyword.value) 
      || obj.countryNameEn.toLowerCase().includes(keyword.value.toLowerCase()))
}, 500, false)

// 搜索代理商
const searchMaster = debounce(()=>{
  masterQuery.value.pageNum = 1
  anchorListStore.getMasterPage()
}, 2000, false)

// 搜索清除
function searchClean(){
    query.value.countryNameCn = ""
    query.value.national = ""
    query.value.nickname = ""
    query.value.userId = ""
    query.value.national = ""
    query.value.date = ""
    query.value.phone = ""
    query.value.masterId = ""
	confirmSearch()
}

// 确定搜索
async function confirmSearch(){
	dataList.value = []
    query.value.pageNum = 1
	loadding.value = true	
    uni.showLoading({mask: true})
	await anchorListStore.getPage().finally(()=>{
      uni.hideLoading()
	  loadding.value = false
   })
}

// 下一页
async function nextPage(){
	if(dataList.value.length < query.value.totalSize){
		query.value.pageNum = query.value.pageNum + 1
		await search()
	}
}

// 搜索
async function search(){
	query.value.totalSize = undefined
	uni.showLoading({mask: true})
	loadding.value = true	
	await anchorListStore.getPage().finally(()=>{
		uni.hideLoading()
		loadding.value = false
	})
}

// 跳转到专辑
function viewAlbum(userId: number){
	 navigate(`${urls.Album}?userId=${userId}`)
}

// 切换状态
async function switchStatus(userId:number, status: number){
	const index = dataList.value.findIndex(e => e.userId === userId)
	if(index != -1){
		uni.showLoading({mask: true})
        await switchStatusApi({userId, status}).then((res:any) => {
			dataList.value[index] = { 
				...dataList.value[index], 
				status: res.data.status, 
				updateTime: res.data.updateTime
			}
		}).catch(err => {
			showError(err.msg || err.errMsg || err)
		}).finally(()=>{
			uni.hideLoading()
		})
	}
}

// 切换隐藏状态
async function switchHide(userId:number, isHide: number){
	const index = dataList.value.findIndex(e => e.userId === userId)
	if(index != -1){
		uni.showLoading({mask: true})
        await switchHideApi({userId, isHide}).then((res:any) => {
			dataList.value[index] = { 
				...dataList.value[index], 
				isHide: res.data.isHide, 
				updateTime: res.data.updateTime
			}
		}).catch(err => {
			showError(err.msg || err.errMsg || err)
		}).finally(()=>{
			uni.hideLoading()
		})
	}
}

// 跳转到更换头像
function changeAvatar(userId:string){
	updateId.value = userId
	navigate(`${urls.UserAvatar}?userId=${userId}`)
}

 // 监听返回结果
function onEvent(){
    uni.$on('avatarRes',function(data){
		if(data.path){
			const target = dataList.value.find(e => e.userId === updateId.value)
			if(target){
				target.avatar = data.path
			}
		}
    })
}

onLoad(()=>{
	nationalStore.init()

	loadding.value = true	
    uni.showLoading({mask: true})
	anchorListStore.init().finally(()=>{
      uni.hideLoading()
	  loadding.value = false
   })

   onEvent()
})

onUnload(()=>{
    uni.$off('avatarRes') 
})
</script>